/**
 * 
 */
package imoney.server.util;

import imoney.shared.CookieBuilderShared;

import javax.servlet.http.Cookie;

import static imoney.shared.Statics.SEPARATOR;
import static imoney.shared.Statics.Cookie_INDEX_OF_PERSON;;

/**
 * A static class used to centralize cookie creation and reading.
 * Cannot be shared with client because of the Cookie object, hence
 * the specific name not to confuse with client side cookie value builder
 * 
 * @author Arnaud PELOQUIN
 *
 */
public class CookieBuilderServer {

	/**
	 * The value of the cookie returned contains the position of the
	 * person in the context list, concatenated with the google userID of the person. When
	 * the cookie is read, the position in the list will be used to fetch the person, 
	 * and then the userIDs will be compared.
	 * If not equal, the client won't be authorized to perform further actions.
	 * @param pseudo the pseudo of the user.
	 */
	public static Cookie buildIndexCookie(String googleID, int positionInList, String pseudo){
		String value = "" + positionInList + SEPARATOR + googleID +
				SEPARATOR + pseudo;
		Cookie cook = new Cookie(Cookie_INDEX_OF_PERSON, value);
		cook.setMaxAge(-1); // the cookie will last forever
		cook.setPath("/");   // commented to conduct some test
		return cook;
	}

	/**
	 * Read the position of the person in the context list stored by this cookie.
	 * @param cook : the cookie to read
	 * @return indexOf, the index corresponding to the person
	 */
	public static int readPosition(Cookie cook){
		if(cook.getName().equals(Cookie_INDEX_OF_PERSON)){
			String rawValue = cook.getValue();
			return CookieBuilderShared.readPosition(rawValue);
		}else{
			System.err.println("CookieBuilder.readPosition : Cookie is of the wrong type. Should be named '"
					+Cookie_INDEX_OF_PERSON+"', but it is : '"+cook.getName()+"'");
			return -1;
		}
	}
	
	/**
	 * Extract the google userID from the value of the cookie.
	 * @param cook : the cookie to read
	 * @return googleID, the string corresponding to the google userID
	 */
	public static String readUserId(Cookie cook){
		if(cook.getName().equals(Cookie_INDEX_OF_PERSON)){
			String rawValue = cook.getValue();
			return CookieBuilderShared.readUserId(rawValue);
		}
		System.err.println("CookieBuilder.readUserId : Cookie is of the wrong type. Should be named '"
				+Cookie_INDEX_OF_PERSON+"', but it is : '"+cook.getName()+"'");
		return "error";
	}
	
	/**
	 * Read the pseudo of the person stored by this cookie.
	 * @param cook : the cookie to read
	 * @return the pseudo
	 */
	public static String readPseudo(Cookie cook){
		if(cook.getName().equals(Cookie_INDEX_OF_PERSON)){
			String rawValue = cook.getValue();
			return CookieBuilderShared.readPseudo(rawValue);
		}else{
			System.err.println("CookieBuilder.readPseudo : Cookie is of the wrong type. Should be named '"
					+Cookie_INDEX_OF_PERSON+"', but it is : '"+cook.getName()+"'");
			return "error";
		}
	}

}
